package com.zzyl.nursing.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.mapper.CheckInConfigMapper;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.service.ICheckInService;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 入住表Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-23
 */
@Transactional
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderServiceImpl elderService;

    @Autowired
    private BedServiceImpl bedService;

    @Autowired
    private ContractServiceImpl contractService;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        //是否有该id的入住信息
        Elder elder = elderService.selectElderById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, checkInElderVo);
        String birthday = elder.getBirthday();
        //求出老人年纪
        checkInElderVo.setAge(LocalDateTime.now().getYear() - Integer.parseInt(birthday.substring(0, 4)));
        //1.回显老人数据
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        //家属响应信息
        //2.回显家属信息,将家属转成集合返回
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        //4.签约办理响应信息
        LambdaQueryWrapper<Contract> contract = Wrappers.<Contract>lambdaQuery()
                .eq(Contract::getElderId, checkIn.getElderId());
        Contract c1 = contractService.getOne(contract);
        checkInDetailVo.setContract(c1);
        //3.入住配置响应信息
        LambdaQueryWrapper<CheckInConfig> checkInConfig = Wrappers.<CheckInConfig>lambdaQuery()
                .eq(CheckInConfig::getCheckInId,id);
        CheckInConfig c = checkInConfigMapper.selectOne(checkInConfig);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(c, checkInConfigVo);
        checkInConfigVo.setBedNumber(elder.getBedNumber());
        checkInConfigVo.setStartDate(c1.getStartDate());
        checkInConfigVo.setEndDate(c1.getEndDate());
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        return checkInDetailVo;
    }

    /**
     * 查询入住表
     * 
     * @param id 入住表主键
     * @return 入住表
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住表列表
     * 
     * @param checkIn 入住表
     * @return 入住表
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住表
     * 
     * @param checkIn 入住表
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住表
     * 
     * @param checkIn 入住表
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住表
     * 
     * @param ids 需要删除的入住表主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住表信息
     * 
     * @param id 入住表主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void apply(CheckInApplyDto dto) {
        // 1.判断老人是否已经入住
        LambdaQueryWrapper<Elder> elderWrapper = Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus, 1);
        Elder one = elderService.getOne(elderWrapper);
        if (one != null) {
            throw new RuntimeException("该老人已入住");
        }
        //2.更新床位的状态
        Bed bed = bedService.selectBedById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedService.updateById(bed);
        //3.新增或更新老人
        Elder elder = insertOrUpdateElder(dto, bed);
        // 生成合同编号
        String contractNo = "HT" + CodeGenerator.generateContractNumber();
        //4.新增签约办理
        insertContract(contractNo,dto,elder);
        //5.新增入住信息
        CheckIn checkIn = insertCheckIn(dto, elder);
        //6.新增入住配置
        insertCheckInConfig(dto,checkIn);
    }


    private void insertCheckInConfig(CheckInApplyDto dto,CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insertCheckInConfig(checkInConfig);
    }

    /*
    *  新增入住信息
    * */
    private CheckIn insertCheckIn(CheckInApplyDto dto,Elder elder) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        checkInMapper.insertCheckIn(checkIn);
        return checkIn;
    }

    /*
    * 4.新增签约办理
    * */
    private void insertContract(String contractNo,CheckInApplyDto dto,Elder elder) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        contract.setContractNumber(contractNo);
        // 状态、开始时间、结束时间
        // 签约时间小于等于当前时间，合同生效中
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
        contract.setStatus(dto.getCheckInConfigDto().getStartDate().isBefore(LocalDateTime.now())?1:0);
        contractService.insertContract(contract);
    }

    private Elder insertOrUpdateElder(CheckInApplyDto dto,Bed bed) {
        Elder elder = new Elder();
        BeanUtils.copyProperties(dto.getCheckInElderDto(), elder);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);
        //查询老人信息，（身份证号、状态不为1）
        LambdaQueryWrapper<Elder> elderWrapper = Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo,dto.getCheckInElderDto().getIdCardNo())
                .ne(Elder::getStatus,1);
        if (ObjectUtils.isEmpty(elderWrapper)){
            //修改老人信息
            elderService.updateElder(elder);
        }else {
            //新增老人信息
            elderService.insertElder(elder);
        }
        return elder;
    }
}






















